package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.dto.BdmBalanceChangeDto;
import com.ruoyi.system.domain.dto.BdmRoyaltyRecordDto;
import com.ruoyi.system.domain.vo.BdmRoyaltyRecordVo;
import com.ruoyi.system.domain.vo.BdmUserVo;
import com.ruoyi.system.domain.vo.StatisticsMineBalanceVo;
import com.ruoyi.system.domain.vo.StatisticsRoyaltyRecordVo;
import com.ruoyi.system.domain.vo.applet.AppletUserBalanceVo;
import com.ruoyi.system.domain.vo.applet.BdmRoyaltyRecordOrderVo;
import com.ruoyi.system.enums.BdmRoyaltyRecordEnum;
import com.ruoyi.system.mapper.BdmRoyaltyRecordMapper;
import com.ruoyi.system.mapper.BdmUserMapper;
import com.ruoyi.system.service.*;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 分销提成记录Service业务层处理
 *
 * @author ruoyi
 * @date 2024-12-09
 */
@Service
public class BdmRoyaltyRecordServiceImpl extends ServiceImpl<BdmRoyaltyRecordMapper,BdmRoyaltyRecord> implements IBdmRoyaltyRecordService
{
    @Autowired
    private BdmRoyaltyRecordMapper bdmRoyaltyRecordMapper;

    @Autowired
    private IBdmTopupRecordService bdmTopupRecordService;

    @Autowired
    private IBdmBalanceChangeService bdmBalanceChangeService;

    @Autowired
    private IBdmUserService bdmUserService;

    @Autowired
    private BdmUserMapper bdmUserMapper;

    @Autowired
    private IBdmBalanceChangeService iBdmBalanceChangeService;

    @Autowired
    private IBdmBalanceRechargeRecordService iBdmBalanceRechargeRecordService;

    /**
     * 查询分销提成记录
     *
     * @param id 分销提成记录主键
     * @return 分销提成记录
     */
    @Override
    public BdmRoyaltyRecord selectBdmRoyaltyRecordById(Long id)
    {
        return bdmRoyaltyRecordMapper.selectBdmRoyaltyRecordById(id);
    }

    /**
     * 查询分销提成记录列表
     *
     * @param bdmRoyaltyRecord 分销提成记录
     * @return 分销提成记录
     */
    @Override
    public List<BdmRoyaltyRecord> selectBdmRoyaltyRecordList(BdmRoyaltyRecord bdmRoyaltyRecord)
    {
        return bdmRoyaltyRecordMapper.selectBdmRoyaltyRecordList(bdmRoyaltyRecord);
    }

    /**
     * 新增分销提成记录
     *
     * @param bdmRoyaltyRecord 分销提成记录
     * @return 结果
     */
    @Override
    public int insertBdmRoyaltyRecord(BdmRoyaltyRecord bdmRoyaltyRecord)
    {
        bdmRoyaltyRecord.setCreateTime(DateUtils.getNowDate());
        return bdmRoyaltyRecordMapper.insertBdmRoyaltyRecord(bdmRoyaltyRecord);
    }

    /**
     * 修改分销提成记录
     *
     * @param bdmRoyaltyRecord 分销提成记录
     * @return 结果
     */
    @Override
    public int updateBdmRoyaltyRecord(BdmRoyaltyRecord bdmRoyaltyRecord)
    {
        bdmRoyaltyRecord.setUpdateTime(DateUtils.getNowDate());
        return bdmRoyaltyRecordMapper.updateBdmRoyaltyRecord(bdmRoyaltyRecord);
    }

    /**
     * 批量删除分销提成记录
     *
     * @param ids 需要删除的分销提成记录主键
     * @return 结果
     */
    @Override
    public int deleteBdmRoyaltyRecordByIds(Long[] ids)
    {
        return bdmRoyaltyRecordMapper.deleteBdmRoyaltyRecordByIds(ids);
    }

    /**
     * 删除分销提成记录信息
     *
     * @param id 分销提成记录主键
     * @return 结果
     */
    @Override
    public int deleteBdmRoyaltyRecordById(Long id)
    {
        return bdmRoyaltyRecordMapper.deleteBdmRoyaltyRecordById(id);
    }

    /**
     * 小程序查询用户收入表
     * @param balanceChangeDto
     * @return
     */
    @Override
    public List<AppletUserBalanceVo> selectUserIncomeList(BdmBalanceChangeDto balanceChangeDto) {
        List<AppletUserBalanceVo> userIncomeVoList = new ArrayList<>();
        Long sysUid = SecurityUtils.getUserId();
        List<BdmBalanceChange> list = bdmBalanceChangeService.lambdaQuery().eq(BdmBalanceChange::getUserId, sysUid)
                .eq(StringUtils.isNotNull(balanceChangeDto.getBusinessType()), BdmBalanceChange::getAddOrSubtract, balanceChangeDto.getBusinessType())
                .ne(BdmBalanceChange::getVariationType, 2)
                .orderByDesc(BdmBalanceChange::getCreateTime, BdmBalanceChange::getId)
                .list();
        if (StringUtils.isNotEmpty(list)) {
            for (BdmBalanceChange change : list) {
                AppletUserBalanceVo vo = new AppletUserBalanceVo();
                vo.setIncomeName(change.getBusinessType());
                vo.setIncomeTime(change.getCreateTime());
                vo.setIncomeMoney(new BigDecimal(change.getVariation()));
                vo.setStatus("已结算");
                vo.setDataType(change.getAddOrSubtract());
                userIncomeVoList.add(vo);
            }
        }
        return userIncomeVoList;
    }

    /**
     * 获取分销提成记录列表
     * @param dto
     * @return
     */
    @Override
    public List<BdmRoyaltyRecordVo> getRoyaltyRecordPage(BdmRoyaltyRecordDto dto) {
        return bdmRoyaltyRecordMapper.getRoyaltyRecordPage(dto);
    }

    @Override
    public List<BdmRoyaltyRecordOrderVo> selectRoyaltyRecord(BdmRoyaltyRecordDto dto) {
        return bdmRoyaltyRecordMapper.selectRoyaltyRecord(dto);
    }

    /**
     * 推广统计
     * @return
     */
    @Override
    public List<StatisticsRoyaltyRecordVo> getStatistics() {
        BdmRoyaltyRecordDto dto = new BdmRoyaltyRecordDto();
        if (!SecurityUtils.hasRole("1")) {
            dto.setUserId(SecurityUtils.getUserId());
        }
        List<StatisticsRoyaltyRecordVo> nullVo = new ArrayList<>();
        StatisticsRoyaltyRecordVo vo = new StatisticsRoyaltyRecordVo();
        vo.setUserId(SecurityUtils.getUserId());
        vo.setTotalAmount(BigDecimal.ZERO);
        vo.setPendingSettlement(BigDecimal.ZERO);
        vo.setAvailableForWithdrawal(BigDecimal.ZERO);
        vo.setWithdrawn(BigDecimal.ZERO);
        nullVo.add(vo);
        BdmUser bdmUser = bdmUserService.lambdaQuery().eq(BdmUser::getSysUserid,SecurityUtils.getUserId()).one();
       // 可提现金额改成：用户余额;
        BigDecimal availableForWithdrawal= ((bdmUser.getRemainingSum())).setScale(2, RoundingMode.HALF_DOWN);
        // 累计提现金额
        BigDecimal withdrawn=(new BigDecimal(bdmUser.getTotalWithdraw()==null?"0.00":bdmUser.getTotalWithdraw()).setScale(2, RoundingMode.HALF_DOWN));

        List<StatisticsRoyaltyRecordVo> voList = bdmRoyaltyRecordMapper.getStatistics(dto);
        if (StringUtils.isEmpty(voList)) {
            vo.setAvailableForWithdrawal(availableForWithdrawal);
            vo.setWithdrawn(withdrawn);
            return nullVo;
        }
        StatisticsRoyaltyRecordVo statisticsRoyaltyRecordVo= voList.get(0);
        // 徐小波更改成用户余额
        // availableForWithdrawal= availableForWithdrawal.subtract(statisticsRoyaltyRecordVo.getPendingSettlement()).setScale(2, RoundingMode.HALF_DOWN);
        statisticsRoyaltyRecordVo.setAvailableForWithdrawal(availableForWithdrawal);
        statisticsRoyaltyRecordVo.setWithdrawn(withdrawn);
        voList.set(0,statisticsRoyaltyRecordVo);
        return voList;
    }

    /**
     * 我的余额统计
     * @return
     */
    @Override
    public StatisticsMineBalanceVo getMineBalance() {
        Long userId = SecurityUtils.getUserId();
        if (StringUtils.isNull(userId)) {
            throw new GlobalException("用户异常");
        }
        StatisticsMineBalanceVo vo = new StatisticsMineBalanceVo();
        vo.setUserId(userId);
        // 收入支出
        BdmUser bdmUser = bdmUserService.lambdaQuery().eq(BdmUser::getSysUserid, userId).one();
        if (StringUtils.isNull(bdmUser)) {
            throw new GlobalException("查询失败，用户异常稍后重试");
        }
        LambdaQueryWrapper<BdmBalanceChange> lqw = new LambdaQueryWrapper<>();
        lqw.select(BdmBalanceChange::getVariation)
                .eq(BdmBalanceChange::getUserId, userId)
                .eq(BdmBalanceChange::getAddOrSubtract, 2);
        List<BdmBalanceChange> ceriationList = bdmBalanceChangeService.list(lqw);
        vo.setTotalAmount(bdmUser.getRemainingSum());
        vo.setExpense(ceriationList.stream().map(BdmBalanceChange::getVariation).filter(Objects::nonNull).map(BigDecimal::new).reduce(BigDecimal.ZERO, BigDecimal::add));
        //////////////////////////
        BdmRoyaltyRecordDto dto = new BdmRoyaltyRecordDto();
        dto.setUserId(SecurityUtils.getUserId());
        bdmUser.setEarnings(bdmRoyaltyRecordMapper.getMineEarnings(dto).get(0).getAvailableForWithdrawal());
        vo.setAvailableForWithdrawal(bdmUser.getEarnings());

        // 提现
        BdmTopupRecord bdmTopupRecord=new BdmTopupRecord();
        bdmTopupRecord.setSysUserid(userId);
        List<BdmTopupRecord> topupRecordList = bdmTopupRecordService.selectBdmTopupRecordList(bdmTopupRecord);
        if (StringUtils.isNotEmpty(topupRecordList)) {
            BigDecimal withdrawn = topupRecordList.stream().filter(t -> !"4".equals(t.getStatus())).map(BdmTopupRecord::getTopupAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
            vo.setWithdrawn(withdrawn);
            vo.setAvailableForWithdrawal(bdmUser.getEarnings());
        }else {
            vo.setWithdrawn(BigDecimal.ZERO);
        }
        List<BdmBalanceRechargeRecord> recordList = iBdmBalanceRechargeRecordService.lambdaQuery().eq(BdmBalanceRechargeRecord::getUserId, userId).eq(BdmBalanceRechargeRecord::getPayState, 2).list();
        if (CollectionUtils.isEmpty(recordList)){
            vo.setTopUp(BigDecimal.ZERO);
        }else {
            vo.setTopUp(recordList.stream().map(BdmBalanceRechargeRecord::getMoney).reduce(BigDecimal.ZERO,BigDecimal::add));
        }

        StatisticsMineBalanceVo mineBalanceVo = baseMapper.getUserTopUpRecord(userId);
        vo.setPendingWithdrawalAmount(mineBalanceVo.getPendingWithdrawalAmount());
        vo.setProcessingPayoutAmount(mineBalanceVo.getProcessingPayoutAmount());
        vo.setCompletedPayoutAmount(mineBalanceVo.getCompletedPayoutAmount());
        vo.setRejectedWithdrawalAmount(mineBalanceVo.getRejectedWithdrawalAmount());
        vo.setPayoutErrorAmount(mineBalanceVo.getPayoutErrorAmount());
        return vo;
    }

    @Override
    public void selectLeaderBrokerage(String orderId) {
        BdmRoyaltyRecord record = new BdmRoyaltyRecord();
        record.setOrderId(orderId);
        record.setStatus("1");
        List<BdmRoyaltyRecord> recordList = bdmRoyaltyRecordMapper.selectBdmRoyaltyRecordList(record);
        if (CollectionUtils.isNotEmpty(recordList)){
            for (BdmRoyaltyRecord bdmRoyaltyRecord : recordList) {
                Long sysUserid = bdmRoyaltyRecord.getSysUserid();
                BigDecimal amount = bdmRoyaltyRecord.getAmount();
                bdmUserService.updateBdmUserMoney(sysUserid,amount);

                bdmRoyaltyRecord.setStatus("2");
                bdmRoyaltyRecordMapper.updateBdmRoyaltyRecord(bdmRoyaltyRecord);

//                BdmUserVo bdmUserVo = bdmUserMapper.getBdmUserByUserId(sysUserid);
//
//                BdmBalanceChange change = new BdmBalanceChange();
//                change.setRelevantDocumentId(bdmRoyaltyRecord.getOrderId());
//                change.setUserId(sysUserid);
//                change.setVariation(amount.toString());
//                change.setVariationBefore(bdmUserVo.getEarnings().toString());
//                change.setVariationAfter(bdmUserVo.getEarnings().add(amount).toString());
//                change.setVariationType(3L);
//                change.setAddOrSubtract(1L);
//                change.setBusinessType(BdmRoyaltyRecordEnum.getEnum(bdmRoyaltyRecord.getType()).getDescription());
//                iBdmBalanceChangeService.insertBdmBalanceChange(change);
            }
        }
    }
}
